﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2022 北京超维景生物科技有限公司 保留所有权利。
 * 
 * 创建者：huangyang
 * 电子邮箱：huangyang@tvscope.cn
 * 创建时间：2023/2/21 14:31:29
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ImageK.Java;
using ImageK.Macros;
using ImageK.Plugin.Filter;
using ImageK.Plugin.Frame;
using ImageK.Util;

namespace ImageK.Gui
{
    /**
     * This class is a customizable modal dialog box. Here is an example
     * GenericDialog with one string field and two numeric fields:
     * <pre>
     *	public class Generic_Dialog_Example implements PlugIn {
     *	  static String title="Example";
     *	  static int width=512,height=512;
     *	  public void run(String arg) {
     *		GenericDialog gd = new GenericDialog("New Image");
     *		gd.addStringField("Title: ", title);
     *		gd.addNumericField("Width: ", width, 0);
     *		gd.addNumericField("Height: ", height, 0);
     *		gd.showDialog();
     *		if (gd.wasCanceled()) return;
     *		title = gd.getNextString();
     *		width = (int)gd.getNextNumber();
     *		height = (int)gd.getNextNumber();
     *		IJ.newImage(title, "8-bit", width, height, 1);
     *	 }
     * }
     * </pre>
    * To work with macros, the first word of each component label must be
    * unique. If this is not the case, add underscores, which will be converted
    * to spaces when the dialog is displayed. For example, change the checkbox labels
    * "Show Quality" and "Show Residue" to "Show_Quality" and "Show_Residue".
    */
    public class GenericDialog:Form
    {
        protected ArrayList numberField, stringField, checkbox, choice, slider, radioButtonGroups;
        protected TextBox textArea1, textArea2;
        protected ArrayList defaultValues, defaultText, defaultStrings, defaultChoiceIndexes;
        protected Label theLabel;
        private Button okay;
        private Button cancel;
        private Button no, help;
        private string helpLabel = "Help";
        private bool _wasCanceled, _wasOKed;
        private int nfIndex, sfIndex, cbIndex, choiceIndex, textAreaIndex, radioButtonIndex;
        // private GridBagConstraints c;
        private bool firstNumericField = true;
        private bool firstSlider = true;
        private bool _invalidNumber;
        private string errorMessage;
        private Hashtable labels;
        private bool macro;
        private string macroOptions;
        private bool _addToSameRow;
        private bool addToSameRowCalled;
        private int topInset, leftInset, bottomInset;
        private bool customInsets;
        private ArrayList sliderIndexes, sliderScales, sliderDigits;
        private CheckBox previewCheckbox;    // the "Preview" Checkbox, if any
        private ArrayList dialogListeners;      // the Objects to notify on user input
        private PlugInFilterRunner pfr;      // the PlugInFilterRunner for automatic preview
        private string previewLabel = " Preview";
        private const string _previewRunning = "wait...";
        private bool recorderOn;          // whether recording is allowed (after the dialog is closed)
        private char echoChar;
        private bool hideCancelButton;
        private bool _centerDialog = true;
        private string helpURL;

        private bool smartRecording;
        private ArrayList imagePanels;
        protected static GenericDialog instance;
        private bool firstPaint = true;
        private bool fontSizeSet;
        private bool showDialogCalled;
        private bool optionsRecorded;     // have dialogListeners been called to record options?
        private Label lastLabelAdded;
        private int[] windowIDs;
        private string[] windowTitles;

        //布局控制
        private TableLayoutPanel _layout = new TableLayoutPanel();
        private int rowIndex = 0;
        private int colIndex = 0;

        public GenericDialog():base()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // GenericDialog
            // 
            this.ClientSize = new System.Drawing.Size(284, 361);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "GenericDialog";
            this.ResumeLayout(false);

        }

        /** Creates a new GenericDialog with the specified title. Uses the current image
        image window as the parent frame or the ImageJ frame if no image windows
        are open. Dialog parameters are recorded by ImageJ's command recorder but
        this requires that the first word of each label be unique. */
        public GenericDialog(string title):this(title, null)
        {
        }

        /** Creates a new GenericDialog using the specified title and parent frame. */
        public GenericDialog(string title, Form parent):this()
        {
            //super(parent, title, true);
            this.Text = title;
            this.AutoSize = true;
            this.AutoSizeMode = AutoSizeMode.GrowOnly;
            _layout.Dock = DockStyle.Fill;
            _layout.Padding = new Padding(3);
            _layout.AutoSize = true;
            _layout.AutoSizeMode = AutoSizeMode.GrowOnly;
            Controls.Add(_layout);

            ImageK ij = IJ.GetInstance();
            // if (ij != null) setFont(ij.getFont());
            okay = new Button()
            {
                Text = "  OK  "
            };
            cancel = new Button()
            {
                Text = "Cancel"
            };
            if (Prefs.blackCanvas)
            {
                // setForeground(SystemColor.controlText);
                // setBackground(SystemColor.control);
            }

            // GridBagLayout grid = new GridBagLayout();
            // c = new GridBagConstraints();
            // setLayout(grid);
            // macroOptions = Macro.getOptions();
            // macro = macroOptions != null;
            // addKeyListener(this);
            // addWindowListener(this);
        }

        /** Adds a numeric field. The first word of the label must be
            unique or command recording will not work.
        * @param label			the label
        * @param defaultValue	value to be initially displayed
        */
        public void addNumericField(string label, double defaultValue)
        {
            int decimalPlaces = (int)defaultValue == defaultValue ? 0 : 3;
            int columnWidth = decimalPlaces == 3 ? 8 : 6;
            addNumericField(label, defaultValue, decimalPlaces, columnWidth, null);
        }

        /** Adds a numeric field. The first word of the label must be
            unique or command recording will not work.
        * @param label			the label
        * @param defaultValue	value to be initially displayed
        * @param digits			number of digits to right of decimal point
        */
        public void addNumericField(string label, double defaultValue, int digits)
        {
            addNumericField(label, defaultValue, digits, 6, null);
        }

        /** Adds a numeric field. The first word of the label must be
            unique or command recording will not work.
        * @param label			the label
        * @param defaultValue	value to be initially displayed
        * @param digits			number of digits to right of decimal point
        * @param columns		width of field in characters
        * @param units			a string displayed to the right of the field
        */
        public void addNumericField(string label, double defaultValue, int digits, int columns, string units)
        {
            string label2 = label;
            if (label2.IndexOf('_') != -1)
                label2 = label2.Replace('_', ' ');
            Label fieldLabel = makeLabel(label2);
            this.lastLabelAdded = fieldLabel;
            if (_addToSameRow)
            {
                // c.gridx = GridBagConstraints.RELATIVE;
                // c.insets.left = 10;
            }
            else
            {
                // c.gridx = 0; c.gridy++;
                // if (firstNumericField)
                //     c.insets = getInsets(5, 0, 3, 0); // top, left, bottom, right
                // else
                //     c.insets = getInsets(0, 0, 3, 0);
                _layout.RowCount += 1;
                rowIndex++;
            }
            // c.anchor = GridBagConstraints.EAST;
            // c.gridwidth = 1;
            //IJ.log("x="+c.gridx+", y= "+c.gridy+", width="+c.gridwidth+", ancher= "+c.anchor+" "+c.insets);
            // add(fieldLabel, c);
            fieldLabel.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
            _layout.Controls.Add(fieldLabel,0,rowIndex);


            if (_addToSameRow)
            {
                // c.insets.left = 0;
                _addToSameRow = false;
            }
            if (numberField == null)
            {
                numberField = new ArrayList(5);
                defaultValues = new ArrayList(5);
                defaultText = new ArrayList(5);
            }
            if (IJ.IsWindows()) columns -= 2;
            if (columns < 1) columns = 1;
            bool scientificNotationAsNeeded = false;
            if (digits < 0)
            {
                digits = -digits;
                scientificNotationAsNeeded = true;
            }
            string defaultString = IJ.d2s(defaultValue, digits);
            if (scientificNotationAsNeeded)
            {
                //todo:
                // defaultString = ij.measure.ResultsTable.d2s(defaultValue, digits);
            }
            if (double.IsNaN(defaultValue))
                defaultString = "";
            TextBox tf = newTextField(defaultString, columns);
            if (IJ.isLinux())
            {
                // tf.setBackground(Color.white);
            }
            // tf.addActionListener(this);
            // tf.addTextListener(this);
            // tf.addFocusListener(this);
            // tf.addKeyListener(this);
            numberField.Add(tf);
            defaultValues.Add(defaultValue);
            defaultText.Add(tf.Text);
            // c.gridx = GridBagConstraints.RELATIVE;
            // c.anchor = GridBagConstraints.WEST;
            // tf.setEditable(true);
            //if (firstNumericField) tf.selectAll();
            firstNumericField = false;
            if (units == null || units.Equals(""))
            {
                // add(tf, c);
                _layout.Controls.Add(tf, 1, rowIndex);
            }
            else
            {
                // Panel panel = new Panel();
                // panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
                // panel.add(tf);
                // panel.add(new Label(" " + units));
                // add(panel, c);
            }
            // if (Recorder.record || macro)
            //     saveLabel(tf, label);
        }

        private Label makeLabel(string label)
        {
            if (IJ.isMacintosh())
                label += " ";
            return new Label(){Text = label};
        }

        /** Saves the label for given component, for macro recording and for accessing the component in macros. */
        private void saveLabel(Object component, String label)
        {
            //todo:
            // if (labels == null)
            //     labels = new Hashtable();
            // if (label.length() > 0)
            //     label = Macro.trimKey(label.trim());
            // if (label.length() > 0 && hasLabel(label))
            // {                       // not a unique label?
            //     label += "_0";
            //     for (int n = 1; hasLabel(label); n++)
            //     {   // while still not a unique label
            //         label = label.substring(0, label.lastIndexOf('_')); //remove counter
            //         label += "_" + n;
            //     }
            // }
            // labels.put(component, label);
        }

        /** Adds an 8 column text field.
        * @param label			the label
        * @param defaultText		the text initially displayed
        */
        public void addStringField(string label, string defaultText)
        {
            addStringField(label, defaultText, 8);
        }

        /** Adds a text field.
        * @param label			the label
        * @param defaultText		text initially displayed
        * @param columns			width of the text field. If columns is 8 or more, additional items may be added to this line with addToSameRow()
        */
        public void addStringField(string label, string defaultText, int columns)
        {
            if (_addToSameRow && label.Equals("_"))
                label = "";
            string label2 = label;
            if (label2.IndexOf('_') != -1)
                label2 = label2.Replace('_', ' ');
            Label fieldLabel = makeLabel(label2);
            this.lastLabelAdded = fieldLabel;
            bool custom = customInsets;
            if (_addToSameRow)
            {
                // c.gridx = GridBagConstraints.RELATIVE;
                _addToSameRow = false;
            }
            else
            {
                // c.gridx = 0; c.gridy++;
                // if (stringField == null)
                //     c.insets = getInsets(5, 0, 5, 0); // top, left, bottom, right
                // else
                //     c.insets = getInsets(0, 0, 5, 0);
                _layout.RowCount += 1;
                rowIndex++;
            }
            // c.anchor = GridBagConstraints.EAST;
            // c.gridwidth = 1;
            fieldLabel.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
            _layout.Controls.Add(fieldLabel,0,rowIndex);
            if (stringField == null)
            {
                stringField = new ArrayList(4);
                defaultStrings = new ArrayList(4);
            }

            TextBox tf = newTextField(defaultText, columns);
            // if (IJ.isLinux()) tf.setBackground(Color.white);
            // tf.setEchoChar(echoChar);
            // echoChar = 0;
            // tf.addActionListener(this);
            // tf.addTextListener(this);
            // tf.addFocusListener(this);
            // tf.addKeyListener(this);
            // c.gridx = GridBagConstraints.RELATIVE;
            // c.anchor = GridBagConstraints.WEST;
            // c.gridwidth = columns <= 8 ? 1 : GridBagConstraints.REMAINDER;
            // c.insets.left = 0;
            // tf.setEditable(true);
            _layout.Controls.Add(tf, 1,rowIndex);
            // add(tf, c);
            stringField.Add(tf);
            defaultStrings.Add(defaultText);
            // tf.setDropTarget(null);
            // new DropTarget(tf, new TextDropTarget(tf));
            // if (Recorder.record || macro)
            //     saveLabel(tf, label);
        }

        /** Sets the echo character for the next string field. */
        public void setEchoChar(char echoChar)
        {
            this.echoChar = echoChar;
        }

        /** Adds a directory text field and "Browse" button, where the
         * field width is determined by the length of 'defaultPath', with
         * a minimum of 25 columns. Use getNextString to retrieve the
         * directory path. Based on the addDirectoryField() method in
         * Fiji's GenericDialogPlus class.
         */
        public void addDirectoryField(String label, String defaultPath)
        {
            int columns = defaultPath!=null ? Math.Max(defaultPath.Length, 25) : 25;
            if (columns>50) columns=50;
            addDirectoryField(label, defaultPath, columns);
        }

        public void addDirectoryField(String label, String defaultPath, int columns)
        {
            defaultPath = IJ.addSeparator(defaultPath);
            addStringField(label, defaultPath, columns);
            if (GraphicsEnvironment.isHeadless())
                return;
            TextBox text = (TextBox)stringField[stringField.Count -1];
            // GridBagConstraints constraints = layout.getConstraints(text);
            // Button button = new Button("Browse", IJ.isMacOSX() ? 10 : 0);
            Button button = new Button
            {
                Text = "Browse",
            };
            //todo:
            // BrowseButtonListener listener = new BrowseButtonListener(label, text, "dir");
            // button.addActionListener(listener);
            FlowLayoutPanel panel = new FlowLayoutPanel();
            panel.FlowDirection = FlowDirection.LeftToRight;
            panel.Controls.Add(text);
            panel.Controls.Add(button);
            // layout.setConstraints(panel, constraints);
            _layout.Controls.Add(panel);
            if (Recorder.OnRecord || macro)
                saveLabel(panel, label);
        }

        private TextBox newTextField(String txt, int columns)
        {
            return new TextBox()
            {
                Text = txt
            };
            // if (IJ.isLinux())
            //     return new TrimmedTextField(txt, columns);
            // else
            //     return new TextBox(txt, columns);
        }


        /** Adds a checkbox.
        * @param label			the label
        * @param defaultValue	the initial state
        */
        public void addCheckbox(string label, bool defaultValue)
        {
            addCheckbox(label, defaultValue, false);
        }

        /** Adds a checkbox; does not make it recordable if isPreview is true.
         * With isPreview true, the checkbox can be referred to as previewCheckbox
         * from hereon.
         */
        private void addCheckbox(string label, bool defaultValue, bool isPreview)
        {
            string label2 = label;
            if (label2.IndexOf('_') != -1)
                label2 = label2.Replace('_', ' ');
            if (_addToSameRow)
            {
                // c.gridx = GridBagConstraints.RELATIVE;
                // c.insets.left = 10;
                _addToSameRow = false;
            }
            else
            {
                // c.gridx = 0; c.gridy++;
                // if (checkbox == null)
                //     c.insets = getInsets(15, 20, 0, 0);  // top, left, bottom, right
                // else
                //     c.insets = getInsets(0, 20, 0, 0);
                _layout.RowCount += 1;
                rowIndex++;
            }
            // c.anchor = GridBagConstraints.WEST;
            // c.gridwidth = 2;
            if (checkbox == null)
                checkbox = new ArrayList(4);
            CheckBox cb = new CheckBox()
            {
                Text = label2,
                AutoSize = true
            };
            cb.Checked = defaultValue;
            // cb.addItemListener(this);
            // cb.addKeyListener(this);
            _layout.Controls.Add(cb, 0, rowIndex);
            _layout.SetColumnSpan(cb,2);
            // add(cb, c);
            // c.insets.left = 0;
            checkbox.Add(cb);
            if (!isPreview && (Recorder.OnRecord || macro)) //preview checkbox is not recordable
                saveLabel(cb, label);
            if (isPreview) previewCheckbox = cb;
        }

        /** Adds a checkbox labelled "Preview" for "automatic" preview.
         * The reference to this checkbox can be retrieved by getPreviewCheckbox()
         * and it provides the additional method previewRunning for optical
         * feedback while preview is prepared.
         * PlugInFilters can have their "run" method automatically called for
         * preview under the following conditions:
         * - the PlugInFilter must pass a reference to itself (i.e., "this") as an
         *	 argument to the AddPreviewCheckbox
         * - it must implement the DialogListener interface and set the filter
         *	 parameters in the dialogItemChanged method.
         * - it must have DIALOG and PREVIEW set in its flags.
         * A previewCheckbox is always off when the filter is started and does not get
         * recorded by the Macro Recorder.
         *
         * @param pfr A reference to the PlugInFilterRunner calling the PlugInFilter
         * if automatic preview is desired, null otherwise.
         */
        public void addPreviewCheckbox(PlugInFilterRunner pfr)
        {
            if (previewCheckbox != null)
                return;
            ImagePlus imp = WindowManager.getCurrentImage();
            if (imp != null && imp.isComposite() && ((CompositeImage)imp).getMode() == IJ.COMPOSITE)
                return;
            this.pfr = pfr;
            addCheckbox(previewLabel, false, true);
        }

        /** Adds a group of checkboxs using a grid layout.
        * @param rows			the number of rows
        * @param columns		the number of columns
        * @param labels			the labels
        * @param defaultValues	the initial states
        */
        public void addCheckboxGroup(int rows, int columns, String[] labels, bool[] defaultValues)
        {
            addCheckboxGroup(rows, columns, labels, defaultValues, null);
        }

        /** Adds a group of checkboxs using a grid layout.
        * @param rows			the number of rows
        * @param columns		the number of columns
        * @param labels			the labels
        * @param defaultValues	the initial states
        * @param headings	the column headings
        * Example: http://imagej.nih.gov/ij/plugins/multi-column-dialog/index.html
        */
        public void addCheckboxGroup(int rows, int columns, String[] labels, bool[] defaultValues, String[] headings)
        {
            TableLayoutPanel panel = new TableLayoutPanel();
            int nRows = headings!=null ? rows+1 : rows;
            panel.RowCount = nRows;
            panel.ColumnCount = columns;
            panel.AutoSize = true;
            panel.AutoSizeMode = AutoSizeMode.GrowOnly;
            // panel.setLayout(new GridLayout(nRows, columns, 6, 0));
            int startCBIndex = cbIndex;
            if (checkbox==null)
                checkbox = new ArrayList(12);
            if (headings!=null)
            {
                // Font font = new Font("SansSerif", Font.BOLD, 12);
                Font font = new Font(new FontFamily("SansSerif"), 12, FontStyle.Bold);
                for (int i = 0; i<columns; i++)
                {
                    if (i>headings.Length-1 || headings[i]==null)
                        panel.Controls.Add(new Label()
                        {
                            Text = ""
                        });
                    else
                    {
                        Label label = new Label()
                        {
                            Text = headings[i]
                        };
                        label.Font = font;
                        panel.Controls.Add(label);
                    }
                }
            }
            int i1 = 0;
            int[] index = new int[labels.Length];
            for (int row = 0; row<rows; row++)
            {
                for (int col = 0; col<columns; col++)
                {
                    int i2 = col*rows+row;
                    if (i2>=labels.Length) break;
                    index[i1] = i2;
                    String label = labels[i1];
                    if (label==null || label.Length==0)
                    {
                        Label lbl = new Label();
                        panel.Controls.Add(lbl);
                        i1++;
                        continue;
                    }
                    if (label.IndexOf('_')!=-1)
                        label = label.Replace('_', ' ');
                    CheckBox cb = new CheckBox()
                    {
                        Text = label
                    };
                    checkbox.Add(cb);
                    cb.Checked = defaultValues[i1];
                    cb.CheckedChanged += CbOnCheckedChanged;
                    if (Recorder.OnRecord || macro)
                        saveLabel(cb, labels[i1]);
                    if (IJ.isLinux())
                    {
                        // Panel panel2 = new Panel();
                        // panel2.setLayout(new BorderLayout());
                        // panel2.add("West", cb);
                        // panel.add(panel2);
                    }
                    else
                        panel.Controls.Add(cb);
                    i1++;
                }
            }
            // c.gridx = 0; c.gridy++;
            // c.gridwidth = GridBagConstraints.REMAINDER;
            // c.anchor = GridBagConstraints.WEST;
            // c.insets = getInsets(10, 0, 0, 0);
            _addToSameRow = false;
            
            _layout.Controls.Add(panel,0,rowIndex);
        }

        private void CbOnCheckedChanged(object? sender, EventArgs e)
        {
            // throw new NotImplementedException();
        }

        /** Adds a popup menu.
        * @param label	the label
        * @param items	the menu items
        * @param defaultItem the menu item initially selected
        */
        public void addChoice(string label, string[] items, string defaultItem)
        {
            string label2 = label;
            if (label2.IndexOf('_') != -1)
                label2 = label2.Replace('_', ' ');
            Label fieldLabel = makeLabel(label2);
            this.lastLabelAdded = fieldLabel;
            if (_addToSameRow)
            {
                // c.gridx = GridBagConstraints.RELATIVE;
                _addToSameRow = false;
            }
            else
            {
                // c.gridx = 0; c.gridy++;
                // if (choice == null)
                //     c.insets = getInsets(5, 0, 5, 0);
                // else
                //     c.insets = getInsets(0, 0, 5, 0);
                _layout.RowCount += 1;
                rowIndex++;
            }
            // c.anchor = GridBagConstraints.EAST;
            // c.gridwidth = 1;
            if (choice == null)
            {
                choice = new ArrayList(4);
                defaultChoiceIndexes = new ArrayList(4);
            }
            // add(fieldLabel, c);
            _layout.Controls.Add(fieldLabel, 0, rowIndex);
            ComboBox thisChoice = new ComboBox();
            // thisChoice.addKeyListener(this);
            // thisChoice.addItemListener(this);
            for (int i = 0; i < items.Length; i++)
                thisChoice.Items.Add(items[i]);
            if (defaultItem != null)
                thisChoice.SelectedItem = defaultItem;
            else
                thisChoice.SelectedIndex = 0;
            // c.gridx = GridBagConstraints.RELATIVE;
            // c.anchor = GridBagConstraints.WEST;
            // add(thisChoice, c);
            _layout.Controls.Add(thisChoice,1,rowIndex);
            choice.Add(thisChoice);
            int index = thisChoice.SelectedIndex;
            defaultChoiceIndexes.Add(index);
            if (Recorder.OnRecord || macro)
                saveLabel(thisChoice, label);
        }

        /** Adds a message consisting of one or more lines of text. */
        public void addMessage(string text)
        {
            addMessage(text, null, Color.Empty);
        }

        /** Adds a message consisting of one or more lines of text,
        which will be displayed using the specified font. */
        public void addMessage(string text, Font font)
        {
            addMessage(text, font, Color.Empty);
        }

        /** Adds a message consisting of one or more lines of text,
        which will be displayed using the specified font and color. */
        public void addMessage(string text, Font font, Color color)
        {
            theLabel = null;
            if (text.IndexOf('\n') >= 0)
                theLabel = new MultiLineLabel(text);
            else
                theLabel = new Label()
                {
                    Text = text
                };
            if (_addToSameRow)
            {
                // c.gridx = GridBagConstraints.RELATIVE;
                _addToSameRow = false;
            }
            else
            {
                // c.gridx = 0; c.gridy++;
                // c.insets = getInsets("".equals(text) ? 0 : 10, 20, 0, 0); // top, left, bottom, right
                _layout.RowCount += 1;
                rowIndex++;
            }
            // c.gridwidth = GridBagConstraints.REMAINDER;
            // c.anchor = GridBagConstraints.WEST;
            // c.fill = GridBagConstraints.HORIZONTAL;
            if (font != null)
            {
                if (Prefs.getGuiScale() > 1.0)
                    font = font.deriveFont((float)(font.Size * Prefs.getGuiScale()));
                theLabel.Font = (font);
            }
            if (color != null)
                theLabel.ForeColor = color;

            _layout.Controls.Add(theLabel, 0, rowIndex);
            // c.fill = GridBagConstraints.NONE;
        }

        /** Adds one or two (side by side) text areas.
         * Append "SCROLLBARS_VERTICAL_ONLY" to the text of
         * the first text area to get vertical scrollbars
         * and "SCROLLBARS_BOTH" to get both vertical and
         * horizontal scrollbars.
         * @param text1 initial contents of the first text area
         * @param text2 initial contents of the second text area or null
         * @param rows	the number of rows
         * @param columns	the number of columns
        */
        public void addTextAreas(string text1, string text2, int rows, int columns)
        {
            if (textArea1 != null) return;
            Panel panel = new Panel();
            ScrollBars scrollbars = ScrollBars.None;
            if (text1 != null && text1.EndsWith("SCROLLBARS_BOTH"))
            {
                scrollbars = ScrollBars.Both;
                text1 = text1.Substring(0, text1.Length - 15);
            }
            if (text1 != null && text1.EndsWith("SCROLLBARS_VERTICAL_ONLY"))
            {
                scrollbars = ScrollBars.Vertical;
                text1 = text1.Substring(0, text1.Length - 24);
            }
            Font font = new Font("SansSerif", (int)(14 * Prefs.getGuiScale()), FontStyle.Regular);
            // textArea1 = new TextArea(text1, rows, columns, scrollbars);
            textArea1 = new TextBox()
            {
                Text = text1,
                Multiline = true,
                ScrollBars = scrollbars
            };
            // if (IJ.isLinux()) textArea1.setBackground(Color.white);
            textArea1.Font = font;
            // textArea1.addTextListener(this);
            panel.Controls.Add(textArea1);
            if (text2 != null)
            {
                // textArea2 = new TextArea(text2, rows, columns, scrollbars);
                textArea2 = new TextBox
                {
                    Text = text2,
                    Multiline = true,
                    ScrollBars = scrollbars
                };
                // if (IJ.isLinux()) textArea2.setBackground(Color.white);
                textArea2.Font = font;
                panel.Controls.Add(textArea2);
            }
            // c.gridx = 0; c.gridy++;
            // c.gridwidth = GridBagConstraints.REMAINDER;
            // c.anchor = GridBagConstraints.WEST;
            // c.insets = getInsets(15, 20, 0, 0);
            _layout.RowCount += 1;
            rowIndex++;

            _addToSameRow = false;
            _layout.Controls.Add(panel, 0, rowIndex);
        }

        /** Adds a Panel to the dialog. */
        public void addPanel(Panel panel)
        {
            // addPanel(panel, GridBagConstraints.WEST, addToSameRow ? c.insets : getInsets(5, 0, 0, 0));
            addPanel(panel, AnchorStyles.Left, new Padding(5, 0, 0, 0));
        }

        /** Adds a Panel to the dialog with custom contraint and insets. The
        defaults are GridBagConstraints.WEST (left justified) and
        "new Insets(5, 0, 0, 0)" (5 pixels of padding at the top). */
        public void addPanel(Panel panel, AnchorStyles constraints, Padding insets)
        {
            if (_addToSameRow)
            {
                // c.gridx = GridBagConstraints.RELATIVE;
                _addToSameRow = false;
            }
            else
            {
                // c.gridx = 0; c.gridy++;
                _layout.RowCount += 1;
                rowIndex++;
            }
            // c.gridwidth = 2;
            // c.anchor = constraints;
            // c.insets = insets;
            // add(panel, c);
            panel.Anchor = constraints;
            panel.Margin = insets;
            _layout.Controls.Add(panel, 0, rowIndex);
        }

        /** Set the insets (margins), in pixels, that will be
            used for the next component added to the dialog
            (except components added to the same row with addToSameRow)
        <pre>
        Default insets:
            addMessage: 0,20,0 (empty string) or 10,20,0
            addCheckbox: 15,20,0 (first checkbox) or 0,20,0
            addCheckboxGroup: 10,0,0
            addRadioButtonGroup: 5,10,0
            addNumericField: 5,0,3 (first field) or 0,0,3
            addStringField: 5,0,5 (first field) or 0,0,5
            addChoice: 5,0,5 (first field) or 0,0,5
         </pre>
        */
        public void setInsets(int top, int left, int bottom)
        {
            topInset = top;
            leftInset = left;
            bottomInset = bottom;
            customInsets = true;
        }

        /** Makes the next item appear in the same row as the previous.
         *	May be used for addNumericField, addSlider, addChoice, addCheckbox, addStringField,
         *	addMessage, addPanel, and before the showDialog() method
         *	(in the latter case, the buttons appear to the right of the previous item).
         *	Note that addMessage (and addStringField, if its column width is more than 8) use
         *	the remaining width, so it must be the last item of a row.
         */
        public void addToSameRow()
        {
            _addToSameRow = true;
            addToSameRowCalled = true;
        }

        /** Sets a replacement label for the "OK" button. */
        public void setOKLabel(string label)
        {
            okay.Text =label;
        }

        /** Displays this dialog box. */
        public void showDialog()
        {
            showDialogCalled = true;
            if (macro)
            {
                // dispose();
                // recorderOn = Recorder.record && Recorder.recordInMacros;
            }
            else
            {
                // if (pfr != null) // prepare preview (not in macro mode): tell the PlugInFilterRunner to listen
                //     pfr.setDialog(this);
                FlowLayoutPanel buttons = new FlowLayoutPanel();
                buttons.FlowDirection = FlowDirection.LeftToRight;
                // buttons.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
                // okay.addActionListener(this);
                // okay.addKeyListener(this);
                okay.Click += actionPerformed;
                if (!hideCancelButton)
                {
                    // cancel.addActionListener(this);
                    // cancel.addKeyListener(this);
                    cancel.Click += actionPerformed;
                }
                if (no != null)
                {
                    // no.addActionListener(this);
                    // no.addKeyListener(this);
                    no.Click += actionPerformed;
                }
                // bool addHelp = helpURL != null;
                // if (addHelp)
                // {
                //     help.setLabel(helpLabel);
                //     help.addActionListener(this);
                //     help.addKeyListener(this);
                // }
                if (IJ.IsWindows() || Prefs.dialogCancelButtonOnRight)
                {
                    buttons.Controls.Add(okay);
                    if (no != null) buttons.Controls.Add(no); ;
                    if (!hideCancelButton)
                        buttons.Controls.Add(cancel);
                    // if (addHelp) buttons.add(help);
                }
                else
                {
                    // if (addHelp) buttons.add(help);
                    // if (no != null) buttons.add(no);
                    // if (!hideCancelButton) buttons.add(cancel);
                    // buttons.add(okay);
                }
                if (_addToSameRow)
                {
                    // c.gridx = GridBagConstraints.RELATIVE;
                }
                else
                {
                    // c.gridx = 0; c.gridy++;
                    _layout.RowCount += 1;
                    rowIndex++;
                }
                // c.anchor = GridBagConstraints.EAST;
                // c.gridwidth = addToSameRowCalled ? GridBagConstraints.REMAINDER : 2;
                // c.insets = new Insets(15, 0, 0, 0);
                // add(buttons, c);
                _layout.Controls.Add(buttons, 0, rowIndex);
                _layout.SetColumnSpan(buttons, 2);
                instance = this;
                // Font font = getFont();
                // if (!fontSizeSet && font != null && Prefs.getGuiScale() != 1.0)
                // {
                //     fontSizeSet = true;
                //     setFont(font.deriveFont((float)(font.getSize() * Prefs.getGuiScale())));
                // }
                // pack();
                // if (okay != null && numberField == null && stringField == null && checkbox == null
                // && choice == null && slider == null && radioButtonGroups == null && textArea1 == null)
                //     okay.Focus()
                // setup();
                // if (centerDialog)
                //     GUI.centerOnImageJScreen(this);
                // setVisible(true);  //except for NonBlockingGenericDialog, returns after 'dispose' by OK or Cancel
                this.ShowDialog();
            }
        }

        /** For plugins that read their input only via dialogItemChanged, call it at least once, then stop recording */
        void finalizeRecording()
        {
            if (optionsRecorded)
                return;
            optionsRecorded = true;
            if (!_wasCanceled && dialogListeners!=null && dialogListeners.Count>0)
            {
                try
                {
                    resetCounters();
                    ((DialogListener)dialogListeners[0]).dialogItemChanged(this, null);
                }
                catch (Exception err)
                {   // for exceptions, don't cover the input by a window
                    IJ.beep();              // but show them at in the "Log"
                    IJ.log("ERROR: "+err+"\nin DialogListener of "+dialogListeners[0]+
                           "\nat "+(err.Message)+"\nfrom "+(err.Source));
                }
                recorderOn = false;
            }
            resetCounters();
        }

        // @Override
        // public void setFont(Font font)
        // {
        //     super.setFont(!fontSizeSet&&Prefs.getGuiScale()!=1.0&&font!=null ? font.deriveFont((float)(font.getSize()*Prefs.getGuiScale())) : font);
        //     fontSizeSet = true;
        // }

        /** Reset the counters before reading the dialog parameters */
        public void resetCounters()
        {
            nfIndex = 0;        // prepare for readout
            sfIndex = 0;
            cbIndex = 0;
            choiceIndex = 0;
            textAreaIndex = 0;
            radioButtonIndex = 0;
            _invalidNumber = false;
        }

        /** Returns the Vector containing the numeric TextFields. */
        public ArrayList getNumericFields()
        {
            return numberField;
        }

        /** Returns the Vector containing the string TextFields. */
        public ArrayList getStringFields()
        {
            return stringField;
        }

        /** Returns the Vector containing the Checkboxes. */
        public ArrayList getCheckboxes()
        {
            return checkbox;
        }

        /** Returns the Vector containing the Choices. */
        public ArrayList getChoices()
        {
            return choice;
        }

        /** Returns the Vector containing the sliders (Scrollbars). */
        public ArrayList getSliders()
        {
            return slider;
        }

        /** Returns the Vector that contains the RadioButtonGroups. */
        public ArrayList getRadioButtonGroups()
        {
            return radioButtonGroups;
        }

        /** Returns a reference to textArea1. */
        public TextBox getTextArea1()
        {
            return textArea1;
        }

        /** Returns a reference to textArea2. */
        public TextBox getTextArea2()
        {
            return textArea2;
        }

        /** Returns a reference to the Label or MultiLineLabel created by the
         *	last addMessage() call. Otherwise returns null. */
        public Component getMessage()
        {
            return theLabel;
        }

        /** Returns a reference to the Preview checkbox. */
        public CheckBox getPreviewCheckbox()
        {
            return previewCheckbox;
        }

        /** Returns 'true' if this dialog has a "Preview" checkbox and it is enabled. */
        public bool isPreviewActive()
        {
            return previewCheckbox!=null && previewCheckbox.Checked;
        }

        /** Returns references to the "OK" ("Yes"), "Cancel",
         * "No", and "Help" buttons as an array of length 4.
         * If a button is not present, the corresponding
         * array element is null.
        */
        public Button[] getButtons()
        {
            return new Button[] { okay, cancel, no, help };
        }

        /** Used by PlugInFilterRunner to provide visable feedback whether preview
         * is running or not by switching from "Preview" to "wait..."
        */
        public void previewRunning(bool isRunning)
        {
            if (previewCheckbox!=null)
            {
                previewCheckbox.Text = isRunning ? _previewRunning : previewLabel;
                if (IJ.isMacOSX()) repaint();   //workaround OSX 10.4 refresh bug
            }
        }

        /** Display dialog centered on the primary screen. */
        public void centerDialog(bool b)
        {
            _centerDialog = b;
        }

        /* Display the dialog at the specified location. */
        public void setLocation(int x, int y)
        {
            this.Location = new Point(x, y);
            _centerDialog = false;
        }

        public void setDefaultString(int index, String str)
        {
            if (defaultStrings!=null && index>=0 && index<defaultStrings.Count)
                defaultStrings[index] = str;
        }

        protected void setup()
        {
        }

        private void actionPerformed(object? sender, EventArgs e)
        {
            if (sender == okay || sender == cancel | sender == no)
            {
                _wasCanceled = sender == cancel;
                _wasOKed = sender == okay;
                // Dispose();
                if (_wasCanceled)
                {
                    DialogResult = DialogResult.Cancel;
                }

                if (_wasOKed)
                {
                    DialogResult = DialogResult.OK;
                }
                Close();
            }
            else if (sender == help)
            {
                //todo:
                // if (hideCancelButton)
                // {
                //     if (helpURL != null && helpURL.equals(""))
                //     {
                //         notifyListeners(e);
                //         return;
                //     }
                //     else
                //     {
                //         wasOKed = true;
                //         dispose();
                //     }
                // }
                // showHelp();
            }
            else
            {
                notifyListeners(e);
            }
        }

        /** Unchanged parameters are not recorder in 'smart recording' mode. */
        public void setSmartRecording(bool smartRecording)
        {
            this.smartRecording = smartRecording;
        }

        /** Add an Object implementing the DialogListener interface. This object will
         * be notified by its dialogItemChanged method of input to the dialog. The first
         * DialogListener will be also called after the user has typed 'OK' or if the
         * dialog has been invoked by a macro; it should read all input fields of the
         * dialog.
         * For other listeners, the OK button will not cause a call to dialogItemChanged;
         * the CANCEL button will never cause such a call.
         * @param dl the Object that wants to listen.
         */
        public void addDialogListener(DialogListener dl)
        {
            if (dialogListeners == null)
                dialogListeners = new ArrayList();
            dialogListeners.Add(dl);
        }

        /** Returns true if the user clicked on "Cancel". */
        public bool wasCanceled()
        {
            //todo:
            // if (_wasCanceled && !Thread.CurrentThread.Name.EndsWith("Script_Macro$"))
            //     Macro.abort();
            return _wasCanceled;
        }

        /** Returns true if the user has clicked on "OK" or a macro is running. */
        public bool wasOKed()
        {
            return _wasOKed || macro;
        }

        /** Returns the contents of the next numeric field,
        or NaN if the field does not contain a number. */
        public double getNextNumber()
        {
            if (numberField == null)
                return -1.0;
            TextBox tf = (TextBox)numberField[nfIndex];
            string theText = tf.Text;
            string label = null;
            if (macro)
            {
                label = (string)labels[(object)tf];
                theText = Macro.getValue(macroOptions, label, theText);
            }
            string originalText = (string)defaultText[nfIndex];
            double defaultValue = ((double)(defaultValues[nfIndex]));
            double value;
            bool skipRecording = false;
            if (theText.Equals(originalText))
            {
                value = defaultValue;
                if (smartRecording) skipRecording = true;
            }
            else
            {
                double d = getValue(theText);
                if (d != double.NaN)
                    value = d;
                else
                {
                    //todo:
                    value = Double.NaN;
                    // Is the value a macro variable?
                    // if (theText.StartsWith("&")) theText = theText.Substring(1);
                    // Interpreter interp = Interpreter.getInstance();
                    // value = interp != null ? interp.getVariable2(theText) : double.NaN;
                    // if (double.IsNaN(value))
                    // {
                    //     invalidNumber = true;
                    //     errorMessage = "\"" + theText + "\" is an invalid number";
                    //     value = Double.NaN;
                    //     if (macro)
                    //     {
                    //         IJ.error("Macro Error", "Numeric value expected in run() function\n \n"
                    //                                 + "	 Dialog box title: \"" + getTitle() + "\"\n"
                    //                                 + "	 Key: \"" + label.toLowerCase(Locale.US) + "\"\n"
                    //                                 + "	 Value or variable name: \"" + theText + "\"");
                    //     }
                    // }
                }
            }
            if (recorderOn && !skipRecording)
            {
                //todo:
                // recordOption(tf, trim(theText));
            }
            nfIndex++;
            return value;
        }

        /** Returns true if one or more of the numeric fields contained an
        invalid number. Must be called after one or more calls to getNextNumber(). */
        public bool invalidNumber()
        {
            bool wasInvalid = _invalidNumber;
            _invalidNumber = false;
            return wasInvalid;
        }

        /** Returns the contents of the next text field. */
        public string getNextString()
        {
            string theText;
            if (stringField == null)
                return "";
            TextBox tf = (TextBox)(stringField[sfIndex]);
            theText = tf.Text;
            string label = labels != null ? (string)labels[(object)tf] : "";
            bool numberExpected = theText != null && theText.Length > 0
                                                     && (char.IsDigit(theText[0]) || theText.StartsWith("-"));
            if (macro)
            {
                // theText = Macro.getValue(macroOptions, label, theText);
                // if (theText != null && (theText.startsWith("&") || numberExpected || label.toLowerCase(Locale.US).startsWith(theText)))
                // {
                //     // Is the value a macro variable?
                //     if (theText.startsWith("&")) theText = theText.substring(1);
                //     Interpreter interp = Interpreter.getInstance();
                //     String s = interp != null ? interp.getVariableAsString(theText) : null;
                //     if (s != null) theText = s;
                // }
            }
            if (recorderOn && !label.Equals(""))
            {
                // String s = theText;
                // if (s != null && s.length() >= 3 && Character.isLetter(s.charAt(0)) && s.charAt(1) == ':' && s.charAt(2) == '\\')
                //     s = s.replaceAll("\\\\", "/");  // replace "\" with "/" in Windows file paths
                // s = Recorder.fixString(s);
                // if (!smartRecording || !s.equals((String)defaultStrings.elementAt(sfIndex)))
                //     recordOption(tf, s);
                // else if (Recorder.getCommandOptions() == null)
                //     Recorder.recordOption(" ");
            }
            sfIndex++;
            return theText;
        }

        /** Returns the state of the next checkbox. */
        public bool getNextBoolean()
        {
            if (checkbox == null)
                return false;
            CheckBox cb = (CheckBox)(checkbox[cbIndex]);
            // if (recorderOn)
            //     recordCheckboxOption(cb);
            bool state = cb.Checked;
            if (macro)
            {
                string label = (string)labels[(object)cb];
                string key = Macro.trimKey(label);
                state = isMatch(macroOptions, key + " ");
            }
            cbIndex++;
            return state;
        }

        // Returns true if s2 is in s1 and not in a bracketed literal (e.g., "[literal]")
        bool isMatch(string s1, string s2)
        {
            if (s1.StartsWith(s2))
                return true;
            s2 = " " + s2;
            int len1 = s1.Length;
            int len2 = s2.Length;
            bool match, inLiteral = false;
            char c;
            for (int i = 0; i < len1 - len2 + 1; i++)
            {
                c = s1[i];
                if (inLiteral && c == ']')
                    inLiteral = false;
                else if (c == '[')
                    inLiteral = true;
                if (c != s2[0] || inLiteral || (i > 1 && s1[i - 1] == '='))
                    continue;
                match = true;
                for (int j = 0; j < len2; j++)
                {
                    if (s2[j] != s1[i + j])
                    { match = false; break; }
                }
                if (match) return true;
            }
            return false;
        }

        /** Returns the selected item in the next popup menu. */
        public string getNextChoice()
        {
            if (choice == null)
                return "";
            ComboBox thisChoice = (ComboBox)(choice[choiceIndex]);
            string item = thisChoice.SelectedItem.ToString();
            if (macro)
            {
                string label = (string)labels[(object)thisChoice];
                item = Macro.getValue(macroOptions, label, item);
                if (item != null && item.StartsWith("&")) // value is macro variable
                    item = getChoiceVariable(item);
            }
            // if (recorderOn)
            //     recordOption(thisChoice, item);
            choiceIndex++;
            return item;
        }

        /** Returns the index of the selected item in the next popup menu. */
        public int getNextChoiceIndex()
        {
            if (choice == null)
                return -1;
            ComboBox thisChoice = (ComboBox)choice[choiceIndex];
            int index = thisChoice.SelectedIndex;
            if (macro)
            {
                //todo:
                // String label = (String)labels.get((Object)thisChoice);
                // String oldItem = thisChoice.getSelectedItem();
                // int oldIndex = thisChoice.getSelectedIndex();
                // String item = Macro.getValue(macroOptions, label, oldItem);
                // if (item != null && item.startsWith("&")) // value is macro variable
                //     item = getChoiceVariable(item);
                // thisChoice.select(item);
                // index = thisChoice.getSelectedIndex();
                // if (index == oldIndex && !item.equals(oldItem))
                // {
                //     // is value a macro variable?
                //     Interpreter interp = Interpreter.getInstance();
                //     String s = interp != null ? interp.getStringVariable(item) : null;
                //     if (s == null)
                //         IJ.error(getTitle(), "\"" + item + "\" is not a valid choice for \"" + label + "\"");
                //     else
                //         item = s;
                // }
            }
            if (recorderOn)
            {
                //todo:
                // int defaultIndex = ((Integer)(defaultChoiceIndexes.elementAt(choiceIndex))).intValue();
                // if (!(smartRecording && index == defaultIndex))
                // {
                //     String item = thisChoice.getSelectedItem();
                //     if (!(item.equals("*None*") && getTitle().equals("Merge Channels")))
                //         recordOption(thisChoice, thisChoice.getSelectedItem());
                // }
            }
            choiceIndex++;
            return index;
        }

        private string getChoiceVariable(string item)
        {
            item = item.Substring(1);
            //todo:
            // Interpreter interp = Interpreter.getInstance();
            // String s = interp != null ? interp.getStringVariable(item) : null;
            // if (s == null)
            // {
            //     double value = interp != null ? interp.getVariable2(item) : Double.NaN;
            //     if (!Double.isNaN(value))
            //     {
            //         if ((int)value == value)
            //             s = "" + (int)value;
            //         else
            //             s = "" + value;
            //     }
            // }
            // if (s != null)
            //     item = s;
            return item;
        }

        protected double getValue(string text)
        {
            double d;
            if (double.TryParse(text, out d))
            {
                return d;
            }
            else
            {
                return double.NaN;
            }
        }

        /** Notify any DialogListeners of changes having occurred
         *	If a listener returns false, do not call further listeners and disable
         *	the OK button and preview Checkbox (if it exists).
         *	For PlugInFilters, this ensures that the PlugInFilterRunner,
         *	which listens as the last one, is not called if the PlugInFilter has
         *	detected invalid parameters. Thus, unnecessary calling the run(ip) method
         *	of the PlugInFilter for preview is avoided in that case.
         */
        private void notifyListeners(EventArgs e)
        {
            if (dialogListeners==null || dialogListeners.Count == 0)
                return;
            bool everythingOk = true;
            for (int i = 0; everythingOk && i<dialogListeners.Count; i++)
            {
                try
                {
                    resetCounters();
                    if (this is NonBlockingGenericDialog)
					    Recorder.resetCommandOptions();
                    if (!((DialogListener)dialogListeners[i]).dialogItemChanged(this, e))
                        everythingOk = false;         // disable further listeners if false (invalid parameters) returned
                } catch (Exception err) {			  // for exceptions, don't cover the input by a window but
				    IJ.beep();							// show them at in the "Log"
				    IJ.log("ERROR: "+err+"\nin DialogListener of "+dialogListeners[i]+
				        "\nat "+(err.Message)+"\nfrom "+(err.Source));
			    }
            }
            resetCounters();
            bool workaroundOSXbug = IJ.isMacOSX() && okay!=null && !okay.Enabled && everythingOk;
            if (everythingOk && recorderOn)
                optionsRecorded = true;
            if (previewCheckbox!=null)
                previewCheckbox.Enabled = everythingOk;
            if (okay!=null)
                okay.Enabled = everythingOk;
            if (workaroundOSXbug)
                repaint(); // OSX 10.4 bug delays update of enabled until the next input
	    }

	    public void repaint()
        {
            //todo:
            // super.repaint();
            // if (imagePanels!=null)
            // {
            //     for (int i = 0; i<imagePanels.size(); i++)
            //         ((ImagePanel)imagePanels.get(i)).repaint();
            // }
        }
        //
        // public void paint(Graphics g)
        // {
        //     super.paint(g);
        //     if (firstPaint && IJ.isMacOSX() && IJ.isJava18())
        //     { // fix for incompletely drawn dialogs on Macs
        //         EventQueue.invokeLater(new Runnable()
        //         {
        //
        //                 public void run()
        //         {
        //             IJ.wait(50);
        //             Dimension size = getSize();
        //             if (size!=null)
        //                 setSize(size.width+2, size.height+2);
        //             firstPaint = false;
        //         }
        //     });
		      //   }
	       //  }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
        }

        /** Adds a "Help" button that opens the specified URL in the default browser.
            With v1.46b or later, displays an HTML formatted message if
            'url' starts with "<html>". There is an example at
            http://imagej.nih.gov/ij/macros/js/DialogWithHelp.js
            If url is an empty String, pressing the "Help" button does nothing except
        calling the DialogListeners (if any). See also: setHelpLabel.
        */
        public void addHelp(String url)
        {
            help = new Button
            {
                Text = helpLabel
            };
            helpURL = url;
        }

        void showHelp()
        {
            //todo:
            // if (helpURL.StartsWith("<html>"))
            // {
            //     string title = Text+" "+helpLabel;
            //     if (this is NonBlockingGenericDialog)
            //         new HTMLDialog(title, helpURL, false); // non blocking
            //     else
            //         new HTMLDialog(this, title, helpURL); //modal
            // }
            // else
            // {
            //     String macro = "call('ij.plugin.BrowserLauncher.open', '"+helpURL+"');";
            //     new MacroRunner(macro); // open on separate thread using BrowserLauncher
            // }
        }
    }
}
